package com.lightsaber.trade.core.service.account.impl;

import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;

import com.google.common.collect.Sets;
import com.lightsaber.trade.core.common.constants.AppConstant;
import com.lightsaber.trade.core.entity.account.Authority;
import com.lightsaber.trade.core.entity.account.Role;
import com.lightsaber.trade.core.entity.account.User;

public class UserDetailsImpl implements org.springframework.security.core.userdetails.UserDetails {

    private static final long serialVersionUID = 1L;

    private User user;
    private String[] roleList;

    public UserDetailsImpl(User user) {
        this.user = user;
        List<Role> roles = user.getRoleList();

        roleList = new String[roles.size()];

        for (int i = 0; i < roles.size(); i++) {
            roleList[i] = roles.get(i).getName();
        }
    }

    public String[] getRoleList() {
        return roleList;
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authSet = Sets.newHashSet();
        for (Role role : user.getRoleList()) {
            for (Authority authority : role.getAuthorityList()) {
                authSet.add(new GrantedAuthorityImpl(AppConstant.AUTHORITY_PREFIX
                        + authority.getName()));
            }
        }

        return authSet;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getLoginId();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
    
    @Override
    public boolean equals(Object rhs) {
        if (rhs instanceof UserDetailsImpl) {
            UserDetailsImpl right = (UserDetailsImpl) rhs;
            return right.getUsername().equals(getUsername());

        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return getUsername().hashCode();
    }

}
